<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, computed } from 'vue';
import examIcon from '#/assets/images/explain-core.png'
import alart from "#/assets/images/alart.svg"
import normalKeyboard from "#/assets/images/normal-keyboard.svg"
import { getExamInfoForUserApi, startExamForUserApi } from '#/api/manage/examination-mgr';
import { useRoute, useRouter } from 'vue-router';
import KeyboardDebugModal from './modules/keyboard-debug-modal.vue';
import { useExamInfo } from './hooks/useApi';
import dayjs from 'dayjs';
import { ElMessage } from 'element-plus';
import { EXAM_SCORE_STATUS } from './const';
import { $t } from '@vben/locales';

const route = useRoute();
const router = useRouter();
const { examInfo, endTime ,refresh} = useExamInfo(route.params.id as string);
const examId = ref();
const startExamLoading = ref(false);
const countdownTimer = ref<NodeJS.Timeout | null>(null);
const showKeyboardDebugModal = ref(false);
// 键盘状态枚举
const KEYBOARD_STATUS = {
  INITIAL: 'initial',    // 初始状态
  ABNORMAL: 'abnormal',  // 异常状态
  NORMAL: 'normal'       // 正常状态
} as const;

// 键盘状态变量
const keyboardStatus = ref<typeof KEYBOARD_STATUS[keyof typeof KEYBOARD_STATUS]>(KEYBOARD_STATUS.INITIAL);

const EXAM_START = $t('examCore.startExam');
const loading = ref(false);

// 添加页面可见性状态跟踪
const isPageVisible = ref(true);
const lastSyncTime = ref(0);
const timeOffset = ref(0); // 本地时间与服务器时间的偏移量

const startEndTime = computed(() => {
  return `${examInfo.value?.beginTime || ''} ~ ${endTime.value || ''}`;
});

// 获取当前准确的服务器时间
const getCurrentServerTime = () => {
  if (!examInfo.value?.currentTime) return new Date();
  
  const now = Date.now();
  const elapsed = now - lastSyncTime.value;
  const serverTime = new Date(examInfo.value.currentTime);
  
  // 计算时间偏移量（仅在首次或长时间未同步时）
  if (lastSyncTime.value === 0 || elapsed > 30000) { // 30秒后重新计算偏移
    timeOffset.value = serverTime.getTime() - now;
    lastSyncTime.value = now;
    console.log('Time offset recalculated:', { 
      serverTime: examInfo.value.currentTime,
      localTime: new Date().toISOString(),
      offset: timeOffset.value,
      elapsed 
    });
  }
  
  const currentServerTime = new Date(now + timeOffset.value);
  console.log('Current server time calculated:', {
    localTime: new Date().toISOString(),
    serverTime: currentServerTime.toISOString(),
    offset: timeOffset.value
  });
  
  return currentServerTime;
};

const examEndCountdown = computed(() => {
  if (!examInfo.value?.currentTime || !examInfo.value?.beginTime) return EXAM_START;
  
  const currentTime = new Date(examInfo.value.currentTime).getTime();
  const startExamTime = new Date(examInfo.value.beginTime).getTime();
  const timeDiff = startExamTime - currentTime;
  
  if (timeDiff <= 0) return EXAM_START;
  
  const totalSeconds = Math.floor(timeDiff / 1000);
  const days = Math.floor(totalSeconds / (3600 * 24));
  const hours = Math.floor((totalSeconds % (3600 * 24)) / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;
  
  return `${days}${$t('common.day')} ${hours}${$t('common.hour')} ${minutes}${$t('common.minute')} ${seconds}${$t('common.second')}`;
});

// 页面可见性变化处理
const handleVisibilityChange = () => {
  const wasVisible = isPageVisible.value;
  isPageVisible.value = !document.hidden;
  
  if (isPageVisible.value && !wasVisible) {
    // 页面重新可见时，调用refresh方法刷新数据
    refresh();
  }
};

// 同步服务器时间
const syncServerTime = async () => {
  if (!examId.value) return;
  
  try {
    // 直接使用服务器时间，不计算偏移量
    if (examInfo.value?.currentTime) {
      console.log('Server time updated:', examInfo.value.currentTime);
    }
  } catch (error) {
    console.error('Failed to sync server time:', error);
  }
};

// 启动倒计时定时器
const startCountdownTimer = () => {
  stopCountdownTimer(); // 先停止现有定时器
  
  countdownTimer.value = setInterval(() => {
    // 只有在页面可见时才更新时间
    if (isPageVisible.value && examInfo.value?.currentTime) {
      // 直接使用服务器时间，每次增加1秒
      const currentTime = new Date(examInfo.value.currentTime);
      currentTime.setTime(currentTime.getTime() + 1000);
      examInfo.value.currentTime = dayjs(currentTime).format('YYYY-MM-DD HH:mm:ss');
    }
    
    // 如果倒计时已结束，停止定时器
    if (examEndCountdown.value === EXAM_START) {
      stopCountdownTimer();
    }
  }, 1000);
};

// 停止倒计时定时器
const stopCountdownTimer = () => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
    countdownTimer.value = null;
  }
};

const isExamStart = computed(() => examEndCountdown.value == EXAM_START)
const isExamEnded = computed(() => {
  if (!endTime.value || !examInfo.value?.currentTime) return false;
  const endTimeDate = new Date(endTime.value).getTime();
  const currentTime = new Date(examInfo.value.currentTime).getTime();
  const beginTimeDate = new Date(examInfo.value?.beginTime ?? '').getTime();
  return endTimeDate >= currentTime && beginTimeDate <= currentTime;
});

const isAbsent = computed(() => {
  return [EXAM_SCORE_STATUS.ABSENT, EXAM_SCORE_STATUS.EXAMINING].includes(examInfo.value?.examScoreStatus);
});

const startExam = () => {
  if (examInfo.value?.configuration?.deviceCheck && keyboardStatus.value !== KEYBOARD_STATUS.NORMAL) {
    ElMessage.error($t('examCore.keyboardDebugRequired'));
    return;
  }
  if (examInfo.value?.examScoreStatus && !isAbsent.value) {
    ElMessage.error($t('examCore.examAlreadyEnded'));
    return;
  }
  startExamLoading.value = true;
  startExamForUserApi(examId.value).then(id => {
    router.push({
      path: `/accreditExam/examStart/${id}`,
      query: {
        examId: examId.value
      }
    });
  }).finally(() => {
    startExamLoading.value = false;
  });
};

// 打开键盘调试弹窗
const openKeyboardDebug = () => {
  showKeyboardDebugModal.value = true;
};

// 处理返回考试
const handleReturnToExam = (isDebugingNormal: boolean) => {
  if (isDebugingNormal) {
    keyboardStatus.value = KEYBOARD_STATUS.NORMAL;
  } else {
    keyboardStatus.value = KEYBOARD_STATUS.ABNORMAL;
  }
};

onMounted(() => {
  examId.value = route.params.id;
  startCountdownTimer();
  // 监听页面可见性变化
  document.addEventListener('visibilitychange', handleVisibilityChange);
});

onUnmounted(() => {
  keyboardStatus.value = KEYBOARD_STATUS.INITIAL;
  stopCountdownTimer();
  // 移除页面可见性变化监听
  document.removeEventListener('visibilitychange', handleVisibilityChange);
});

const tipImg = computed(() => {
  return keyboardStatus.value === KEYBOARD_STATUS.NORMAL ? normalKeyboard : alart;
});
const tipText = computed(() => {
  switch (keyboardStatus.value) {
    case KEYBOARD_STATUS.ABNORMAL:
      return $t('examCore.keyboardDebugAbnormal');
    case KEYBOARD_STATUS.NORMAL:
      return $t('examCore.keyboardDebugCompleted');
    default:
      return $t('examCore.ensureDeviceNormal');
  }
});
</script>

<template>
  <div class="explain-core w-full h-full flex flex-col items-center bg-[#f5f6fa] py-4 overflow-y-hidden"
    v-loading="loading">
    <!-- 头部信息区：左右两栏紧凑布局 -->
    <div class="w-full max-w-[1200px] bg-white rounded-lg mb-4 px-5 py-3 flex justify-between items-stretch">
      <!-- 左侧三栏 -->
      <div class="flex flex-1 min-w-0 items-center">
        <!-- 图标栏 -->
        <div class="flex items-center justify-center w-16">
          <div class="w-16 h-16 rounded-full flex items-center justify-center">
            <img :src="examIcon" :alt="$t('examCore.courseIcon')" class="w-[56px] h-[56px] object-contain" />
          </div>
        </div>
        <!-- 课程名和课程内容栏 -->
        <div class="flex flex-col justify-between h-full max-w-[260px] ml-3">
          <div class="text-xl font-bold leading-tight truncate" :title="examInfo?.name">{{ examInfo?.name }}</div>
          <div
            class="text-sm mt-1 truncate text-[#191919]"
            :title="examInfo?.courseName"
          >
            <span class="text-[#595959]">{{ $t('examCore.course') }}</span>
            {{ examInfo?.courseName }}
          </div>
        </div>
        <!-- 考试时间和地点栏 -->
        <div class="flex flex-col justify-between min-w-0 ml-4 h-full">
          <div class="flex items-center justify-center bg-[#efadb033] rounded pl-1 pr-5 py-0.5 min-w-93 max-w-96">
            <span class="text-sm px-2 py-0.5 text-[rgba(25, 25, 25, 0.5)] w-17">{{ $t('examCore.examTime') }}</span>
            <span class="text-sm text-[#E5484D] font-medium flex-1">{{ startEndTime }}</span>
          </div>
          <div class="flex">
            <div class="text-sm text-[#191919] truncate text-center pr-6"><span class="text-[#595959]">{{ $t('examCore.certification') }}</span> <span
                class="ml-1" :title="examInfo?.certificationName">{{examInfo?.certificationName ?? '--'}}</span></div>
            <div class="text-sm text-[#191919] truncate text-center"><span class="text-[#595959]">{{ $t('examCore.examLocation') }}</span>
              <span class="ml-1" :title="examInfo?.location || ''">{{ examInfo?.location ?? '--'}}</span></div>
          </div>
        </div>
      </div>
      <!-- 右侧两行 -->
      <div class="flex items-center min-w-[220px] justify-end" v-if="isAbsent">
        <div class="flex items-center gap-2 mr-6" v-if="!isExamStart">
          <span class="text-[#191919] text-sm">{{ $t('examCore.timeToExamStart') }}</span>
          <span class="text-[#1677ff] text-base font-bold">{{ examEndCountdown}}</span>
        </div>
        <!-- 0067d133 可以 -->
        <el-button @click="startExam" :disabled="!isExamEnded" :color="isExamEnded ? '#0067d133' : '#dcdfe6'"
          :class="isExamEnded ? `text-[#0067d1]` : 'text-[#909399]'" :loading="startExamLoading">
          {{examInfo?.status !== 'end' ? $t('examCore.startExam') : $t('examCore.examEndTxt') }}
        </el-button>
      </div>
      <div v-if="!isAbsent && examInfo?.examScoreStatus" class="flex items-center justify-end">
        <div class="text-xl text-[#909399] font-bold">
          {{ $t('examCore.examEndTxt') }}
        </div>
      </div>
    </div>
    <!-- 考试说明和键盘调试提示独占一行，分割线 -->
    <div class="w-full max-w-[1200px] bg-white rounded-lg shadow-sm flex-1 min-h-0 flex flex-col">
      <div class="flex items-center justify-between h-[50px] px-6">
        <div class="text-[16px] font-bold">{{ $t('examCore.examInstruction') }}</div>
        <div class="flex items-center gap-2 text-sm" v-if="examInfo?.configuration?.deviceCheck && isAbsent">
          <img :src="tipImg" alt="" />
          <span v-html="tipText"></span>
          <a href="#" @click.prevent="openKeyboardDebug" class="text-[#0067D1] ml-2"
            v-if="keyboardStatus != KEYBOARD_STATUS.NORMAL">{{ $t('examCore.goDebugDevice') }}</a>
        </div>
      </div>
      <hr class="border-t border-gray-200 mb-6" />
      <div class="text-sm text-gray-800 leading-7 px-6 pb-8 whitespace-pre-line overflow-y-auto flex-1">
        {{ examInfo?.description }}
      </div>
    </div>

    <!-- 键盘调试弹窗 -->
    <KeyboardDebugModal v-model:visible="showKeyboardDebugModal" @return-to-exam="handleReturnToExam" />
  </div>
</template>

<style lang="less" scoped>
</style>
